package ru;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

public class DoubleArrayReader implements Iterator<double[]> {
    final BufferedReader reader;
    String currentString = null;

    public DoubleArrayReader(final String fileName) throws FileNotFoundException {
        this.reader = new BufferedReader(new FileReader(fileName));
    }

    public DoubleArrayReader(final BufferedReader reader) {
        this.reader = reader;
    }

    public boolean hasNext() {
        refresh();
        return currentString != null;
    }

    public double[] next() {
        refresh();
        final double[] result = parse(currentString);
        currentString = null;
        return result;
    }

    void refresh() {
        try {
            if (currentString == null) {
                currentString = reader.readLine();
            }
            if (currentString == null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    double[] parse(final String string) {
        String[] tmp = string.split(" ");
        double[] x = new double[tmp.length];
        for (int i = 0; i < x.length; i++) {
            if (tmp[i].length() > 0) {
                x[i] = Double.parseDouble(tmp[i]);
            }
        }
        return x;
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}